<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>付款</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery.qrcode/1.0/jquery.qrcode.min.js"></script>
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
    <!-- 引入 layui.css -->
    <link rel="stylesheet" href="//unpkg.com/layui@2.6.8/dist/css/layui.css"></script>
    <!-- 引入 layui.js -->
    <script src="//unpkg.com/layui@2.6.8/dist/layui.js"></script>
    <script src="https://unpkg.com/coco-message/coco-message.min.js"></script>
    <script>
        // 获取 URL 参数
        function getUrlParameter(name) {
            name = name.replace(/[$$$$]/g, "\\$&");
            var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)");
            var results = regex.exec(window.location.href);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, " "));
        }

        // 在页面加载时获取传递过来的参数
        window.onload = function() {
            const propertyId = getUrlParameter('propertyId');
            const staffId = getUrlParameter('staffId');
            console.log("房产ID:", propertyId);
            console.log("操作员ID:", staffId);
            $("#propertyId").val(propertyId); // 将房产ID赋值到输入框中
            $("#staffId").val(staffId); // 将操作员ID赋值到输入框中
            selectPropertyByPropertyId(propertyId);
            $('#price').on('input', function() {
                var price = parseFloat($(this).val());
                if(price) {
                    $("#priceSpan").html(price.toFixed(2) + "元")
                    $("#priceSpan1").html("¥" + price.toFixed(2))
                } else {
                    price=0;
                    $("#priceSpan").html(price.toFixed(2) + "元")
                }
            });
        }
        // 根据房产ID查询房产信息
        function selectPropertyByPropertyId(propertyId) {
            $.ajax({
                url: "/property/selectPropertyByPropertyId",
                data: JSON.stringify({
                    'propertyId': propertyId
                }),
                contentType: "application/json",
                dataType: "json",
                type: "post",
                success: function (resp) {
                    console.log(resp)
                    if (resp.code === 200) {
                        console.log(resp.msg)
                        $("#electricityBalance").val(resp.data.electricityBalance);
                        $("#waterBalance").val(resp.data.waterBalance);
                        $("#ownerId").val(resp.data.ownerId);
                        selectOwnerByOwnerId(resp.data)
                    } else {
                        console.log(resp)
                    }
                },
                error:function(xhr,type,errorThrown){
                    console.log('XMLHttpRequest 对象:',xhr);
                    console.log('错误类型:', type);
                    console.log('错误描述:', errorThrown);
                }
            })
        }
        // 根据业主ID查询业主信息
        function selectOwnerByOwnerId(property) {
            $.ajax({
                url: "/owner/selectOwnerByOwnerId",
                data: JSON.stringify({
                    'ownerId': property.ownerId
                }),
                contentType: "application/json",
                dataType: "json",
                type: "post",
                success: function (resp) {
                    console.log(resp)
                    if (resp.code === 200) {
                        console.log(resp.msg)
                        addPropertyInfo(property, resp.data);
                    } else {
                        console.log(resp)
                    }
                },
                error:function(xhr,type,errorThrown){
                    console.log('XMLHttpRequest 对象:',xhr);
                    console.log('错误类型:', type);
                    console.log('错误描述:', errorThrown);
                }
            })
        }
        function addPropertyInfo(property, owner) {
            $("<tr></tr>").html(
                '<td> ' + property.buildings + "栋" + '</td>' +
                '<td> ' + property.unitInfo + "单元" + '</td>' +
                '<td> ' + property.floor + "层" + '</td>' +
                '<td> ' + property.roomNumber + "室" + '</td>' +
                '<td> ' + owner.ownerName + '</td>' +
                '<td> ' + owner.contactInfo + '</td>' +
                '<td> ' + (property.waterBalance).toFixed(3) + '</td>' +
                '<td> ' + (property.electricityBalance).toFixed(3) + '</td>'
            ).appendTo($("#propertyInfo"))
        }
    </script>
    <style>
        .line {
            display: inline-block; /* 将伪元素设定为块级元素 */
            height: 40px; /* 竖线的高度 */
            border-left: 1px solid #808080; /* 竖线的样式 */
            margin: 0 10px; /* 调整竖线与图片、文字之间的距离 */
        }
        .container {
            display: flex;
            justify-content: space-around; /* 将子元素平均分布在容器中 */
        }

        .my-div {
            border: none;
            padding: 10px;
            margin: 5px;
            display: flex; /* 将my-div设置为Flex容器 */
            align-items: center; /* 垂直居中 */
        }
    </style>
</head>
<body>
    <input id="propertyId" type="hidden">
    <input id="electricityBalance" type="hidden">
    <input id="waterBalance" type="hidden">
    <input id="ownerId" type="hidden">
    <input id="staffId" type="hidden">
    <div class="page-header" style="display: flex; align-items: center; margin-top: 10px; margin-bottom: 0; padding: 0;">
        <img src="/img/logo.png" alt="logo" style="width: 150px;">
        <span class="line"></span>
        <span style="font-size: 20px; color: #808080">充值界面</span>
    </div>
    <hr class="layui-border-black">
    <blockquote class="layui-elem-quote">房产信息</blockquote>
    <table class="layui-table" lay-skin="line">
        <colgroup>
            <col width="150">
            <col width="200">
            <col>
        </colgroup>
        <thead>
        <tr>
            <th>楼栋</th>
            <th>单元</th>
            <th>楼层</th>
            <th>门牌号</th>
            <th>业主姓名</th>
            <th>联系方式</th>
            <th>水卡余额¥</th>
            <th>电卡余额¥</th>
        </tr>
        </thead>
        <tbody id="propertyInfo">
        </tbody>
    </table>
    <blockquote class="layui-elem-quote">充值类型</blockquote>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <input type="radio" name="rechargeType" value="1" title="电卡充值" checked>
            <img src="/img/eleLogo.jpg" alt="电卡充值" style="width: 80px; border: 1px solid #ccc;">
            <input type="radio" name="rechargeType" value="2" title="水卡充值">
            <img src="/img/waterLogo.jpg" alt="水卡充值" style="width: 80px; border: 1px solid #ccc;">
        </div>
    </div>
    <blockquote class="layui-elem-quote">支付方式</blockquote>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <input type="radio" name="payStyle" value="1" title="支付宝" checked>
            <img src="/img/alipayLogo.png" alt="支付宝支付" style="width: 80px; border: 1px solid #ccc;">
        </div>
    </div>
    <blockquote class="layui-elem-quote">充值金额</blockquote>
    <form class="layui-form">
        <div class="layui-input-block">
            <input type="text" id="price" name="price" style="width: 200px" required placeholder="请输入充值金额" class="layui-input" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').replace(/(\.\d\d)\d+/, '$1')">
        </div>
    </form>
    <hr class="layui-border-red">
    <blockquote class="layui-elem-quote layui-quote-nm">
        <div class="container">
            <div class="my-div"><span>天峰物业</span></div>
            <div class="my-div"><span>充值金额：</span>
                <span style="color: red;" id="priceSpan">0.00元</span>
            </div>
            <div class="my-div">
                <button type="button" class="layui-btn layui-btn-radius layui-btn-danger" onclick="confirmPayment()">立即支付</button>
            </div>
        </div>
    </blockquote>

    <!-- 支付提示页面 -->
    <div class="modal fade" id="alipayModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">支付提示</h4>
                </div>
                <div class="modal-body" style="background-color: #dfdfdf; display: flex; flex-direction: column; align-items: center;">
                    <div style="margin-bottom: 20px;">
                        <img src="/img/alipay.jpg" height="20px">
                        支付宝扫码支付
                    </div>
                    <div style="background-color: white; width: 300px; height: 300px; padding: 22px;" >
                        <div id="alipayQrCode"></div>
                    </div>
                    <div>
                        实付：<span id="priceSpan1" style="color: red;"></span>
                    </div>
                    <div id="countdown"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-danger" data-dismiss="modal">我已支付</button>
                </div>
            </div>
        </div>
    </div>

</body>
<script>
    // 设置倒计时时长为5分钟（以秒为单位）
    let countdownTime = 5 * 60;
    let countdownElement = document.getElementById('countdown');

    function updateCountdown() {
        let minutes = Math.floor(countdownTime / 60);
        let seconds = countdownTime % 60;

        countdownElement.textContent = `支付时间：${minutes < 10 ? '0' : ''}${minutes}:${seconds < 10 ? '0' : ''}${seconds}`;

        countdownTime--;

        if (countdownTime < 0) {
            clearInterval(timer);
            countdownElement.textContent = '二维码失效';
        }
    }

    let timer = setInterval(updateCountdown, 1000); // 每秒更新倒计时
</script>
<!--  跳转充值页面  -->
<script>
    let qrcodeStatus = "不存在支付二维码";
    function confirmPayment() {
        if (qrcodeStatus === "不存在支付二维码") {
            // 获取选中的充值类型的值
            const rechargeType = $('input[type=radio][name=rechargeType]:checked').val();
            // 获取选中的支付方式的值
            const payStyle = $('input[type=radio][name=payStyle]:checked').val();
            const price = $("#price").val(); // 获取要充值的金额
            let payStyleMsg;
            let subject;
            if (payStyle === "1") {
                payStyleMsg = "支付宝"
            }
            if (rechargeType === "1") {
                subject = "电费"
            } else{
                subject = "水费"
            }
            if (price) {
                console.log("充值开始")
                console.log(subject, payStyleMsg, price)
                layer.confirm("确定要充值" + subject + "吗?", {icon: 3, title:'提示'}, function(index){
                    var closeMsg = cocoMessage.loading(true);
                    setTimeout(function() {
                        closeMsg();
                        paymentQrcode(subject, price)
                    }, 3000);
                    layer.close(index);
                });
            } else {
                console.log("请输入充值金额！")
                cocoMessage.warning("请输入充值金额!");
            }
        } else {
            $("#alipayModal").modal('show'); // 打开支付页面
        }
    }
    // 生成支付二维码
    function paymentQrcode(subject, price) {
        console.log("商品标题:" + subject)
        console.log("金额:" + price)
        $.ajax({
            url: "/property/alipayQrcode",
            data: {
                "subject": subject,
                "price": price
            },
            dataType: "json",
            type: "post",
            success: function (resp) {
                console.log(resp)
                $("#alipayQrCode").empty();
                jQuery("#alipayQrCode").qrcode({
                    text: resp.qrcode.data,
                    render: 'canvas', // 设置渲染方式，可选
                    size: 100 // 设置二维码大小，可选
                })
                qrcodeStatus = "存在支付二维码"
                updateCountdown(); // 首次更新倒计时
                $("#alipayModal").modal('show'); // 打开支付页面
                // 查询是否已经扫码支付成功
                let intervalId = setInterval(function () {
                    confirmAlipay(resp.flowingWater, function(data) {
                        console.log("data:", data)
                        if (data === "TRADE_SUCCESS") {
                            clearInterval(intervalId); // 停止查询
                            cocoMessage.success("支付成功!");
                            const closeMsg = cocoMessage.loading(true);
                            setTimeout(function() {
                                updatePropertyEleAndWater(resp.flowingWater); // 修改水电费信息
                                closeMsg();
                            }, 3000);
                            $("#alipayModal").modal('hide'); // 关闭支付页面
                        }
                    })
                }, 1000); // 每隔一秒查询一次是否支付成功
            },
            error:function(xhr,type,errorThrown){
                console.log('XMLHttpRequest 对象:',xhr);
                console.log('错误类型:', type);
                console.log('错误描述:', errorThrown);
            }
        })
    }
    // 确认是否扫码支付成功
    function confirmAlipay(flowingWater, callback) {
        $.ajax({
            url: "/property/confirmAlipay",
            data: {
                "flowingWater": flowingWater
            },
            dataType: "json",
            type: "post",
            success: function (resp) {
                let data = resp.data.data;
                if (data === "TRADE_SUCCESS") {
                    console.log(resp);
                }
                callback(data)
            },
            error:function(xhr,type,errorThrown){
                console.log('XMLHttpRequest 对象:',xhr);
                console.log('错误类型:', type);
                console.log('错误描述:', errorThrown);
            }
        })
    }
    // 修改水电费信息
    function updatePropertyEleAndWater(flowingWater) {
        let propertyId = $("#propertyId").val(); // 获取房产ID
        let electricityBalance = parseFloat($("#electricityBalance").val()); // 获取当前电卡余额
        let waterBalance = parseFloat($("#waterBalance").val()); // 获取当前水费余额
        let price = parseFloat($("#price").val()); // 获取要充值的金额
        var updateElectricityBalance = null;
        var updateWaterBalance = null;
        // 获取选中的充值类型的值
        const rechargeType = $('input[type=radio][name=rechargeType]:checked').val();
        if (rechargeType === "1") {
            updateElectricityBalance = electricityBalance + price;
        } else{
            updateWaterBalance = waterBalance + price;
        }
        $.ajax({
            url: "/property/recharge",
            data: JSON.stringify({
                "propertyId": propertyId,
                "waterBalance": updateWaterBalance,
                "electricityBalance": updateElectricityBalance
            }),
            contentType: "application/json",
            dataType: "json",
            type: "post",
            success: function (resp) {
                console.log(resp)
                if (resp.code === 200) {
                    addPaymentRecord(flowingWater); // 生成缴费记录
                } else {
                    cocoMessage.error(resp.msg);
                }
            },
            error:function(xhr,type,errorThrown){
                console.log('XMLHttpRequest 对象:',xhr);
                console.log('错误类型:', type);
                console.log('错误描述:', errorThrown);
            }
        })
    }
    // 生成缴费记录
    function addPaymentRecord(flowingWater) {
        let propertyId = $("#propertyId").val(); // 获取房产ID
        let ownerId = $("#ownerId").val(); // 获取业主ID
        // 获取选中的充值类型的值
        const rechargeType = $('input[type=radio][name=rechargeType]:checked').val();
        let price = parseFloat($("#price").val()); // 获取要充值的金额
        let staffId = $("#staffId").val(); // 获取操作员ID
        $.ajax({
            url: "/paymentRecord/insert",
            data: JSON.stringify({
                "flowingWater": flowingWater,
                "ownerId": ownerId,
                "propertyId": propertyId,
                "itemId": rechargeType,
                "paymentAmount": price,
                "staffId": staffId
            }),
            contentType: "application/json",
            dataType: "json",
            type: "post",
            success: function (resp) {
                console.log(resp)
                if (resp.code === 200) {
                    cocoMessage.success("缴费记录生成成功!")
                } else {
                    cocoMessage.error("缴费记录生成失败!")
                }
                window.close();
            },
            error:function(xhr,type,errorThrown){
                console.log('XMLHttpRequest 对象:',xhr);
                console.log('错误类型:', type);
                console.log('错误描述:', errorThrown);
            }
        })
    }
</script>
</html>